package com.zangchat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.core.domain.AjaxResult;
import com.common.utils.StringUtils;
import com.zangchat.domain.ChatUsers;
import com.zangchat.domain.mongoBean.MCommentBean;
import com.zangchat.domain.mongoBean.MTrendsBean;
import com.zangchat.service.IChatUsersService;
import com.zangchat.service.IMongoDbService;
import com.zangchat.service.IPageInfoService;
import com.zangchat.utils.COSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zangchat.mapper.ChatTrendsMapper;
import com.zangchat.domain.ChatTrends;
import com.zangchat.service.IChatTrendsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.function.Consumer;

/**
 * 广场动态 服务层实现
 *
 * @author ruoyi
 * @date 2020-07-22
 */
@Service
public class ChatTrendsServiceImpl extends ServiceImpl<ChatTrendsMapper, ChatTrends> implements IChatTrendsService {
    @Autowired
    private ChatTrendsMapper chatTrendsMapper;
    @Autowired
    private IMongoDbService mongoDbService;
    @Autowired
    private IPageInfoService pageInfoService;
    @Autowired
    private IChatUsersService usersService;

    /**
     * 发布动态
     *
     * @param userId
     * @param trendLimit
     * @param trendsContenttai
     * @param gallery
     * @param trendsType
     * @param relayId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult releaseTrends(Long userId, Integer trendLimit, String trendsContenttai, String gallery, Integer trendsType, Long relayId, Integer type) {
        ChatTrends chatTrends = new ChatTrends();
        chatTrends.setCreateTime(new Date());
        chatTrends.setDataFlag(1);
        chatTrends.setTrendLimit(trendLimit);
        chatTrends.setTrendsContenttai(trendsContenttai);
        chatTrends.setUserId(userId);
        chatTrends.setTrendsType(trendsType);
        if (trendsType == 1) {
            chatTrends.setRelayId(0L);
        } else {
            chatTrends.setRelayId(relayId);
        }

//        String[] galleryUrl = gallery.split(",");
//        String newGalleryUrl="";
//        if (type.equals("2")) {
//            for (String urls : galleryUrl) {
//                Map<String, Object> urlImgSize = COSClientUtil.getUrlImgSize(urls);
//                if (newGalleryUrl.equals("")) {
//                    newGalleryUrl = urls + "|" + urlImgSize.get("width") + "|" + urlImgSize.get("height");
//                } else {
//                    newGalleryUrl = newGalleryUrl + "," + urls + "|" + urlImgSize.get("width") + "|" + urlImgSize.get("height");
//                }
//            }
//        }
        chatTrends.setGallery(gallery);
        chatTrends.setType(type);
        int insert = baseMapper.insert(chatTrends);
        if (insert > 0) {
            MTrendsBean trendsBean = new MTrendsBean();
            trendsBean.setId(UUID.randomUUID()+"");
            trendsBean.setTrendsId(chatTrends.getTrendsId());
            trendsBean.setDataFlag(1);
            List<MCommentBean> comment=new ArrayList<>();
//            comment.add(new MCommentBean());
            trendsBean.setComment(comment);
            mongoDbService.saveTrends(trendsBean);
            return AjaxResult.success("发布动态成功");
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return AjaxResult.error("动态发送失败");
    }


    /**
     * 用户评论
     *
     * @param userId
     * @param content
     * @param targetId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult userComment(Long userId, String content, String targetId) {
        String[] targetArray = targetId.split("-");
        MTrendsBean trends = mongoDbService.getTrendsById(targetArray[0]);
        MCommentBean commentBean = new MCommentBean();
        commentBean.setCommentId(UUID.randomUUID().toString());
        commentBean.setUserId(userId);
        commentBean.setTrendsId(Long.valueOf(targetArray[0]));
        commentBean.setToCommentId(Long.valueOf(targetArray[1]));
        commentBean.setContent(content);
        commentBean.setCreateTime(new Date());
        if (StringUtils.isNull(trends)) {
            MTrendsBean trendsBean = new MTrendsBean();
            trendsBean.setId(UUID.randomUUID().toString());
            trendsBean.setDataFlag(1);
            trendsBean.setTrendsId(Long.valueOf(targetArray[0]));
            List<MCommentBean> comment = new ArrayList<>();
            comment.add(commentBean);
            trendsBean.setComment(comment);
            AjaxResult ajaxResult = mongoDbService.updateTrendById(trendsBean);
            return AjaxResult.success("评论成功", ajaxResult.get("data"));
        } else {
            List<MCommentBean> comment = trends.getComment();
            comment.add(commentBean);
            trends.setComment(comment);
            AjaxResult ajaxResult = mongoDbService.updateTrendById(trends);
            return AjaxResult.success("评论成功", ajaxResult.get("data"));
        }
//            AjaxResult ajaxResult = mongoDbService.updateTrendById(maps);
//        }
    }

    /**
     * 查看动态圈
     *
     * @param userId
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Override
    public AjaxResult trendsList(Long userId, Integer pageSize, Integer pageNum, String type) {
        if (StringUtils.isNull(pageSize)) {
            pageSize = 4;
        }
        if (StringUtils.isNull(userId)) {
            userId = 0L;
        }
        pageInfoService.initPagePageHelper(pageNum, pageSize);
        ChatTrends where = new ChatTrends();
        if (type.equals("2")) {
            if (userId != 0L) {
                where.setUserId(userId);
            } else {
                return AjaxResult.notLogin();
            }
        }
        where.setTrendLimit(Integer.parseInt(type));
        where.setDataFlag(1);
        List<ChatTrends> chatTrendList = chatTrendsMapper.selectListByWhere(where);
        List<Map<String, Object>> list = new ArrayList<>();
        //循环重新赋值
        for (ChatTrends chatTrends : chatTrendList) {
            Map<String, Object> map = new HashMap<>();
            map.put("trendId", chatTrends.getTrendsId());
            map.put("createTime", chatTrends.getCreateTime());
            map.put("gallery", chatTrends.getGallery());
            map.put("type", chatTrends.getType());
            map.put("trendsContenttai", chatTrends.getTrendsContenttai());
            map.put("userId", chatTrends.getUserId());
            //查询用户的名称和头像信息
            ChatUsers users = usersService.getUsersDataById(chatTrends.getUserId());
            map.put("userName", users.getUserName());
            map.put("headImg", users.getHeadImg());
            map.put("sex", users.getSex());
            //查询动态的评论条数
            MTrendsBean trendsById = mongoDbService.getTrendsById(chatTrends.getTrendsId() + "");
            if (StringUtils.isNull(trendsById)) {
                map.put("commentCount", 0);
            } else {
                List<MCommentBean> comment = trendsById.getComment();
                map.put("commentCount", comment.size());
            }
            list.add(map);
        }
        Map<String, Object> map = pageInfoService.initPageInfo(list);
        return AjaxResult.success("获取成功", map);
    }

    /**
     * 获取评论列表
     *
     * @param userId
     * @param targetId
     * @return
     */
    @Override
    public AjaxResult trendsCommentList(Long userId, String targetId) {
        ChatTrends where = new ChatTrends();
        where.setTrendsId(Long.valueOf(targetId));
        where.setDataFlag(1);
        QueryWrapper<ChatTrends> qw = new QueryWrapper<>(where);
        ChatTrends chatTrends = baseMapper.selectOne(qw);
        if (StringUtils.isNull(chatTrends)) {
            return AjaxResult.error("动态不存在");
        }
        MTrendsBean trendsBean = mongoDbService.getTrendsById(chatTrends.getTrendsId() + "");
        Map<String,Object> trendsComment=new HashMap<>();
        trendsComment.put("trendsId", chatTrends.getTrendsId());
        trendsComment.put("userId", chatTrends.getUserId());
        trendsComment.put("trendsContenttai", chatTrends.getTrendsContenttai());
        trendsComment.put("gallery", chatTrends.getGallery());
        trendsComment.put("createTime", chatTrends.getCreateTime());
        trendsComment.put("trendsType", chatTrends.getTrendsType());
        trendsComment.put("type", chatTrends.getType());
        trendsComment.put("trendLimit", 1);
        trendsComment.put("trendsComment",trendsBean);
        return AjaxResult.success("获取成功", trendsComment);
    }


}